package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.aiassistant.domain.entity.AiContactEntity;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.model.PaasFormDataEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.EnableApiCallBack;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.ApiCallBackEnum;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.ContactDao;
import com.xbongbong.saas.domain.entity.ext.ContactEntityExt;
import com.xbongbong.saas.enums.OnlyInsertDBEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.DistributorContactEnum;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.model.ContactSubDataModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.toolbox.help.OnlyInsertDBHelp;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;


/**
 * @author feng.zheng
 * @version v1.0
 * @date 2019/1/14 15:37
 * @since v1.0
 */
@Service("contactModel")
public class ContactModelImpl implements ContactModel {

    @Resource
    private ShowFormatHelp showFormatHelp;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private ContactDao contactDao;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private PaasFormDataEsModel paasFormDataEsModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private ContactSubDataModel contactSubDataModel;

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CONTACT, operateTypeEnum = OperateTypeEnum.NEW)
    public Integer insert(ContactEntityExt entity) throws XbbException {
        //TODO  先进行数据库的插入动作
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_CONTACT_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = contactDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);

        OnlyInsertDBHelp.filterData(XbbRefTypeEnum.CONTACT.getCode(), DistributorMarkEnum.OTHER.getCode(), paasFormDataEntity.getData());
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_CONTACT);
        paasEsModel.insert(insertDTO);

        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_CONTACT_SUB);
        return success;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CONTACT, operateTypeEnum = OperateTypeEnum.EDIT)
    public Integer update(ContactEntityExt contactEntity) throws XbbException {
        long now = DateUtil.getInt();
        contactEntity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(contactEntity, IndexTypeEnum.IDX_SAAS_CONTACT_SUB);
        StandardizeDataUtil.standardizeNotString(contactEntity);
        Integer success = contactDao.update(contactEntity);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(contactEntity, IndexTypeEnum.IDX_SAAS_CONTACT_SUB);
        if (Objects.equals(1, success) || Objects.equals(1, updateSub)) {
            // 更新时间
            success = contactDao.updateTime(now + 1, contactEntity.getId(), contactEntity.getCorpid());
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            paasFormDataEntity = (PaasFormDataEntity) CloneUtil.deepClone(contactEntity);
            OnlyInsertDBHelp.filterData(XbbRefTypeEnum.CONTACT.getCode(), DistributorMarkEnum.OTHER.getCode(), paasFormDataEntity.getData());
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_CONTACT);
            insertDTO.getSource().remove("creatorId");
            paasEsModel.update(insertDTO);
        }
        if (Objects.nonNull(contactEntity.getSubFormData()) && !contactEntity.getSubFormData().isEmpty()) {
            contactEntity.getData().putAll(contactEntity.getSubFormData());
        }

        return success;
    }

    @Override
    public List<ContactEntityExt> findEntitys(Map<String, Object> param) {
        List<ContactEntityExt> entitys = contactDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_CONTACT_SUB);
        }
        return entitys;
    }

    @Override
    public List<ContactEntityExt> getFixConnectorContact(String corpid, Long startId, Integer pageSize) {
        List<ContactEntityExt> entitys = contactDao.getFixConnectorContact(corpid, startId, pageSize);
        return entitys;
    }

    @Override
    public List<ContactEntityExt> getFixContactLinkCustomerName(String corpid, Long startId, Integer pageSize) {
        List<ContactEntityExt> entitys = contactDao.getFixContactLinkCustomerName(corpid, startId, pageSize);
        return entitys;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return contactDao.getEntitysCount(param);
    }

    @Override
    public ContactEntityExt getByKey(Long key, String corpid) {
        ContactEntityExt contactEntityExt = contactDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(contactEntityExt), IndexTypeEnum.IDX_SAAS_CONTACT_SUB);
        return contactEntityExt;
    }

    /**
     * 查询客户通话记录时拿出所有隶属联系人id
     *
     * @param corpid     公司id
     * @param customerId 客户ID
     * @return List<Integer> 联系人id列表
     */
    @Override
    public List<Long> getCallLogCustomerContactIdList(String corpid, Integer customerId, Integer pageSize) throws XbbException{
        List<Long> contactIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        // 模糊查询 类似于sql中的like
        QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery("data."+ ContactEnum.CUSTOMER_NAME.getAttr(), customerId);
        boolQueryBuilder.filter(queryBuilder);
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_CONTRACT.getType()));
        sourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CONTRACT.getIndex());
        List<String> fieldList = Arrays.asList(FieldTypeEnum.DATAID.getAlias());
        EsUtil.setFieldList(sourceBuilder, fieldList);
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, BasicConstant.ONE, pageSize);
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<ContactEntityExt> contactEntityExtList = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, ContactEntityExt.class);
        if (!Objects.equals(contactEntityExtList.getContent().size(), BasicConstant.ZERO)) {
            contactEntityExtList.getContent().forEach(contactEntityExt -> contactIdIn.add(contactEntityExt.getDataId()));
        }
        // 鸥翔：查询通话记录时能拿到已被删除的联系人的通话记录
        return contactIdIn;
    }

    /**
     * 按手机号查询联系人
     *
     * @param corpid 公司ID
     * @param phone  用于判重的手机号
     * @return CustomerEntityExt
     * @author youli.chen
     * @date 2019/1/23 20:27
     * @since v1.0
     */
    @Override
    public ContactEntityExt getByPhone(String corpid, String phone) throws XbbException{
        if (StringUtil.isEmpty(phone)) {
            return null;
        }
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        //解析查询条件
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        // 电话拨打，采用精确查询
        boolQueryBuilder.filter(termQuery("data."+ ContactEnum.PHONE.getAttr() + "." + StringConstant.PHONE_TEL_ATTR + ".keyword", phone));

        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CONTACT.getType()));
        sourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CONTACT.getIndex());
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, 1);
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<ContactEntityExt> contactEntityExtList = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, ContactEntityExt.class);
        if (contactEntityExtList.getContent().size() == 0) {
            return null;
        } else {
            ContactEntityExt contactEntityExt = contactEntityExtList.getContent().get(0);
            paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(contactEntityExt), IndexTypeEnum.IDX_SAAS_CONTACT_SUB);
            return contactEntityExt;
        }
    }

    /**
     * 根据id删除联系人
     *
     * @param key    主键
     * @param corpid 公司id
     * @return java.lang.Integer
     * @author feng.zheng
     * @date 2019/2/22 20:23
     */
    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CONTACT, operateTypeEnum = OperateTypeEnum.DELETE)
    public Integer deleteByKey(Long key, String corpid) throws XbbException {
        Integer integer = contactDao.deleteByKey(key, corpid);
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+ key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_CONTACT);
        paasEsModel.delete(deleteDTO);

        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_CONTACT_SUB);
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CONTACT, operateTypeEnum = OperateTypeEnum.DELETE, isBatch = true)
    public Integer deleteBatch(List<Long> idIn, String corpid) throws XbbException {
        Integer integer = contactDao.deleteBatch(idIn, corpid);
        paasEsModel.deleteBatch(idIn, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_CONTACT);

        paasFormSubDataModel.deleteBatchByDataId(idIn, corpid, IndexTypeEnum.IDX_SAAS_CONTACT_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CONTACT, operateTypeEnum = OperateTypeEnum.DELETE, isBatch = true)
    public Integer deleteBatch(List<Long> idIn, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer integer = contactDao.deleteBatch(idIn, corpid);
        paasEsModel.deleteBatch(idIn, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_CONTACT, refreshPolicy);

        paasFormSubDataModel.deleteBatchByDataId(idIn, corpid, IndexTypeEnum.IDX_SAAS_CONTACT_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CONTACT, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = contactDao.updateBatch(updateList, corpid);
            // 批量数据处理
            for (UpdateDataEntity updateDataEntity : updateList) {
                updateDataEntity.getData().removeIf(item -> OnlyInsertDBEnum.containBusinessTypeAttr(XbbRefTypeEnum.CONTACT.getCode(), item.getKey().replace("$.", ""), DistributorMarkEnum.OTHER.getCode()));
            }
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_CONTACT);
        }
        if (!subList.isEmpty()) {
            contactSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CONTACT, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = contactDao.updateBatch(updateList, corpid);
            // 批量数据处理
            for (UpdateDataEntity updateDataEntity : updateList) {
                if (CollectionsUtil.isNotEmpty(updateDataEntity.getData())) {
                    updateDataEntity.getData().removeIf(item -> OnlyInsertDBEnum.containBusinessTypeAttr(XbbRefTypeEnum.CONTACT.getCode(), item.getKey().replace("$.", ""), DistributorMarkEnum.OTHER.getCode()));
                }
            }
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_CONTACT, refreshPolicy);
        }
        if (!subList.isEmpty()) {
            contactSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, boolean needThrow) throws XbbException {
        Integer integer = contactDao.updateBatch(updateList, corpid);
        paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_CONTACT, needThrow);
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CONTACT, operateTypeEnum = OperateTypeEnum.NEW, isBatch = true)
    public void insertBatch(List<PaasFormDataEntity> contactEntityExtList, boolean isImport) throws XbbException {
        for (PaasFormDataEntity paasFormDataEntity : contactEntityExtList) {
            paasFormSubDataModel.transferSubForm(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_CONTACT_SUB);
        }
        StandardizeDataUtil.standardize4EntityList(contactEntityExtList);
        contactDao.insertBatch(contactEntityExtList);
        //ES数据插入
        List<InsertDTO> insertList = new ArrayList<>();
        for (PaasFormDataEntity item : contactEntityExtList) {
            item.getData().remove(FieldTypeEnum.OWNERID.getAlias());
            item.getData().remove(FieldTypeEnum.COUSERID.getAlias());
            // 批量数据处理
            OnlyInsertDBHelp.filterData(XbbRefTypeEnum.CONTACT.getCode(), DistributorMarkEnum.OTHER.getCode(), item.getData());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(item.getCorpid() + "_" + item.getId());
            item.setDataId(item.getId());
            insertDTO.setSource(BeanUtil.convertBean2Map(item, true, true));
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_CONTACT);
            insertList.add(insertDTO);
        }
        if (isImport) {
            paasEsModel.insertBatch(insertList, WriteRequest.RefreshPolicy.NONE);
        } else {
            paasEsModel.insertBatch(insertList);
        }

        paasFormSubDataModel.insertBatchSubFormData(contactEntityExtList, IndexTypeEnum.IDX_SAAS_CONTACT_SUB);

    }

    /**
     * 数据还原
     * @param dataIdList
     * @param corpid
     * @param del
     * @throws XbbException
     */
    @Override
    public Integer restoreBatch(List<Long> dataIdList, String corpid, Integer del) throws XbbException {
        Integer count = contactDao.restoreBatch(dataIdList, corpid, del);
        updateBatchDel(dataIdList, corpid, del);

        paasFormSubDataModel.restoreBatch(dataIdList, corpid, IndexTypeEnum.IDX_SAAS_CONTACT_SUB);
        return count;
    }

    @Override
    public List<AiContactEntity> getContactList4Ai(String corpid, List<Long> idIn) {
        return contactDao.getContactList4Ai(corpid, idIn);
    }

    private void updateBatchDel(List<Long> dataIdList, String corpid, Integer del) throws XbbException{
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("del", del);
        map.put("updateTime",DateTimeUtil.getInt());
        paasFormDataEsModel.updateBatch(dataIdList, corpid, map, IndexTypeEnum.IDX_SAAS_CONTACT);
    }

    @Override
    public List<ContactEntityExt> findEntitysWithoutSub(Map<String, Object> param) {
        return contactDao.findEntitys(param);
    }

    /**
     * 编辑时将获取数据格式化
     *
     * @param saasAnalysisDataDTO saas编辑数据
     * @param result               要返回的jsonobject
     * @throws XbbException 业务异常
     * @author feng.zheng
     * @date 2019/1/22 15:28
     */
    @Override
    public void formatData(SaasAnalysisDataDTO saasAnalysisDataDTO, JSONObject result) throws XbbException {
        showFormatHelp.formatLinkBusiness4Show(result, ContactEnum.CUSTOMER_NAME.getAttr(), ContactEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), ContactEnum.CUSTOMER_NAME.getFieldType());
        // 格式化生日
        showFormatHelp.formatBirthday4Show(result, ContactEnum.BIRTHDAY.getAttr(), ContactEnum.BIRTHDAY_FLAG.getAttr());
    }

    @Override
    public void formatDataForDistributor(SaasAnalysisDataDTO saasAnalysisDataDTO, JSONObject result) throws XbbException {
        showFormatHelp.formatLinkBusiness4Show(result, DistributorContactEnum.DISTRIBUTOR_NAME.getAttr(), DistributorContactEnum.DISTRIBUTOR_NAME_LINK_TEXT.getAttr(), DistributorContactEnum.DISTRIBUTOR_NAME.getFieldType());
        // 格式化生日
        showFormatHelp.formatBirthday4Show(result, DistributorContactEnum.BIRTHDAY.getAttr(), DistributorContactEnum.BIRTHDAY_FLAG.getAttr());
    }

    @Override
    public List<ContactEntityExt> listByInPhone(String corpid, List<String> phoneList) throws XbbException {
        if (CollectionUtils.isEmpty(phoneList)) {
            return new ArrayList<>();
        }
        Set<String> phoneSet = phoneList.stream().filter(StringUtil::isNotEmpty).collect(Collectors.toSet());
        if (CollectionsUtil.isEmpty(phoneSet)) {
            return new ArrayList<>();
        }
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        //解析查询条件
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        // 电话拨打，采用精确查询
        boolQueryBuilder.filter(QueryBuilders.termsQuery("data."+ ContactEnum.PHONE.getAttr() + "." + StringConstant.PHONE_TEL_ATTR + ".keyword", phoneSet));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CONTACT.getType()));
        sourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CONTACT.getIndex());
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, 500);
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<ContactEntityExt> contactEntityExtList = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, ContactEntityExt.class);
        List<ContactEntityExt> content = contactEntityExtList.getContent();
        if (CollectionUtils.isEmpty(content)) {
            return new ArrayList<>();
        }
        paasFormSubDataModel.findSubEntity(corpid, content, IndexTypeEnum.IDX_SAAS_CONTACT_SUB);
        return content;
    }
    public Integer updateTime(Long id,String corpid) throws XbbException {
        long now = DateTimeUtil.getInt();
        // 更新时间
        Integer success = contactDao.updateTime(now, id, corpid);
        // 更新es
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        paasFormDataEntity.setId(id);
        paasFormDataEntity.setDataId(id);
        paasFormDataEntity.setCorpid(corpid);
        paasFormDataEntity.setUpdateTime(now);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_CONTACT);
        paasEsModel.update(insertDTO);
        return success;
    }

}


